import { fileSizeApi, downloadFileApi, downloadChunkApi } from '@/api/file'
import { localDownload, getChunkArgs, formatSize, CHUNK_SIZE } from '@/utils/fileUtil'
import { ref } from 'vue'
import { sleep } from '@/utils/func'

export const useDownloader = () => {
  const percent = ref(-2) // -2: 待下载, -1: 准备中, 0: 准备就绪
  const size = ref(0) // 已下载的大小
  const pause = ref(false)

  const download = async (filePath: string, fileName: string) => {
    const file: File = await getFile(filePath, fileName)
    localDownload(file, file.name)
  }

  const getFile = async (filePath: string, fileName: string) => {
    percent.value = -1
    size.value = 0
    pause.value = false
    const fileSize = await fileSizeApi(filePath)
    const chunks: Blob[] = []
    if(fileSize > CHUNK_SIZE) {
      const chunkArgs = getChunkArgs(fileSize)
      percent.value = 0
      for(const i in chunkArgs) {
        while(pause.value) await sleep(100)

        const { offset, length } = chunkArgs[i]
        const chunk = await downloadChunkApi(filePath, offset, length)
        chunks.push(chunk)
        size.value += length
        percent.value = parseFloat(((size.value / fileSize) * 100).toFixed(2))
      }
    } else {
      const chunk = await downloadFileApi(filePath)
      chunks.push(chunk)
      size.value = fileSize
      percent.value = 99
    }

    percent.value = 100
    return new File(chunks, fileName)
  }

  return { download, getFile, formatSize, percent, size, pause }
}
